const rp = require("request-promise-native")
const fs = require("fs")
const mongoose = require("mongoose")
const Movie = mongoose.model("Movie")
const Category = mongoose.model("Category")
var fastXmlParser = require('fast-xml-parser');

async function fetchMovie(item) {
    const url = `https://douban-api.uieee.com/movie/subject/${item.doubanID}`
    const res = await rp(url)
    // Xml
    let body

    try{
        body  = JSON.stringify(res)
        
    }catch (err){
        console.log(err)
    }
    // console.log(typeof(res))
    return body
}

; (async () => {
    let movies = await Movie.find({
        $or: [
            { summary: { $exists: false } },
            { summary: null },
            { title: "" },
            {year:""},
            { summary: '' }
        ]
    })
    console.log(movies)
    for (let i = 0; i < movies.length; i++) {
        
        let movie = movies[i]
        let movieData = await fetchMovie(movie)
        // movieData = JSON.parse(movieData)
        movieData =  fastXmlParser.parse(movieData)
        // movieData = JSON.stringify(movieData)
        console.log(movieData)

        if (movieData) {
            console.log("得到电影数据了啊")
            // console.log(movieData)
            console.log(typeof(movieData) )
            // let a = movieData.getElementsByTagName("db:attribute")[0].getAttribute("title")
            // console.log(a)
            console.log(movieData.title)
            console.log("得到电影数据了啊")
            let tags = movieData.tag || []

            movie.tags = movie.tags || []
            movie.summary = movieData.summary || ""
            movie.title =  movieData.title || ""
            movie.rawTitle = movieData.title || movieData.rawTitle || ''

            if (movieData.attributes ) {
                console.log("得到attrs了啊")
                console.log(1)
                movie.movieTypes = movieData.attrs.movie_type || []
                movie.year = movie.attrs.year || 2500
                for (let i = 0;i<movie.movieTypes.length;i++){
                    let element = movie.movieTypes[i]
                    let cat = await Category.findOne({
                        name: element
                    })
                    if (!cat) {
                        cat = new Category({
                            name: element,
                            movies: [movie._id]
                        })
                    } else {
                        if (cat.movies.indexOf(movie._id) === -1) {//indexOf查找第一次出现的下标,大于-1表示有这个元素
                            cat.movies.push(movie._id)
                        }
                    }
    
                    await cat.save()

                    if(!movie.category){
                        movie.category.push(cat._id)
                    }else{
                        if(movie.category.indexOf(cat._id)===-1){
                            movie.category.push(cat._id)
                        }
                    }
                }
            // movie.movieTypes.forEach(async element => {
               
            

                let dates = movieData.attrs.pubdate || []
                let pubdate = []

                dates.map(async item => {
                    if (item != '' && item.split('(').length > 0) {
                        //把日期和国家拆开
                        let pasts = item.split("(")
                        let date = pasts[0]
                        let courty = '未知'
                        if (pasts[1]) {
                            courty = pasts[1]
                        }
                        pubdate.push(
                            {
                                date: new Date(date),
                                courty
                            }
                        )
                    }
                })

                movie.pubdate = pubdate
            }
            tags.forEach(tag => {
                movie.tags.push(tag.name)
            })  
            console.log('打印电影了啊')
            console.log(movie)
            // await movie.save()
        }
    }

})()

